<?php

namespace app\admin_module\controllers;

use app\exceptions\Exception;
use app\models\Admin;
use yii\web\Controller;
use Yii;
use app\common\Helpers;

class PublicController extends CommonController
{

    public $layout=false;
    protected $noLogin = ['signin'];

    /**
     * @return string
     * @throws \yii\base\ExitException
     * 登录
     */
    public function actionSignin()
    {
        $model=new Admin();
        if(Yii::$app->request->isPost){
            //post过来的数据，视为登录操作
            $post=Yii::$app->request->post();
            try {
                if($model->login($post)){
                    //登录成功，进行跳转
                    $this->redirect(['default/index']);
                    Yii::$app->end();
                }
            } catch (\Exception $e) {
                Yii::$app->session->setFlash('info',$e->getMsg());
            }

        }
        return $this->render('signin',['model'=>$model]);
    }

    /**
     * 退出
     */
    public function actionLogout()
    {
        Yii::$app->session->removeAll();
        if(!isset(Yii::$app->session['admin']['isLogin'])){
            $this->redirect(['public/signin']);
            Yii::$app->end();
        }
        $this->goBack();

    }
    /**
     * 找回密码
     */
    public function actionSeekpassword()
    {
        $model=new Admin();
        if(Yii::$app->request->isPost){
            //post过来的数据，视为找回密码操作
            $post=Yii::$app->request->post();
            if($model->seekPass($post)){
                //登录成功，进行跳转
                $this->redirect(['public/signin']);
                Yii::$app->end();
            }
        }
        return $this->render('seekpassword',['model'=>$model]);
    }


    /**
     * 通过邮箱修改链接
     */
    public function actionChangePassByEmail()
    {
        $get=Yii::$app->request->get();
        Helpers::emptyArr($get,['timestamp','name','token']);

        if(time()-$get['timestamp']>600){
            //过期
            $this->redirect(['public/signin']);
            Yii::$app->end();
        }
        $model=new Admin();
        if($model->createToken($get['name'],$get['timestamp']) !=$get['token']){
            //token错误
            $this->redirect(['public/signin']);
            Yii::$app->end();
        }
        if(Yii::$app->request->isPost){
            //重置密码提交
            if($model->changePass(Yii::$app->request->post())){
                Yii::$app->session->setFlash('info','密码修改成功');
                $this->redirect(['public/signin']);
                Yii::$app->end();

            }else{
                Yii::$app->session->setFlash('info','密码修改失败');

            }


        }
        $model->name=$get['name'];
        return $this->render('changepassbyemail',['model'=>$model]);
    }


}
